import styles from "./dialog-list.module.scss";
import { DialogListItem } from "./dialog-list-item";
import { DialogResizeableSidebar } from "@/app/components/dialog/dialog-resizeable-sidebar";
import { useNavigate } from "react-router-dom";
import { userChatStore } from "@/app/store/chat-store";
import { DialogHead } from "@/app/components/dialog/dialog-head";
import { useEffect, useState } from "react";
import { DialogType } from "@/types/chat";

/**
 * 对话框列表
 */
export function DialogList() {
    const navigate = useNavigate();
    const chatStore = userChatStore();
    const [sessions, currentSessionIndex, selectSession, currentSession] = userChatStore(
        (state) => [
            state.sessions,
            state.currentSessionIndex,
            state.selectSession,
            state.currentSession
        ]
    );
    useEffect(() => {
        if (sessions.length > 0) {
            selectSession(currentSessionIndex);
            navigate(`/chat/${currentSession().id}`, {
                state: {title: currentSession().dialog.title},
            });
        }
    }, []);

    // 测试
    
    const [selected, setSelected] = useState<DialogType>();
    

    return (
        // DialogResizeableSidebar 用于调整对话栏的大小
        <div>
            {/*头部操作*/}
            <DialogHead />
            

            <div className={styles["dialog-list"]}>
                {/*循环遍历数据，当有数据变更时会自动刷新到页面*/}
                {sessions.map((session, index) => (
                    <DialogListItem
                        key={session.id}
                        session={session}
                        selected={currentSessionIndex == index}
                        onClick={() => {
                            selectSession(index);
                            navigate(`/chat/${session.id}`, {state: {title: session.dialog.title}})
                        }}
                        onClickDelete={() => {
                            chatStore.deleteSession(index);
                        }}
                    />
                ))}
            </div>
        </div>
    );

}